use std::io::{Error, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;

fn handle_client(mut stream: TcpStream) -> Result<(), Error>{
    //创建一个数组
    let mut buf = [0; 512];
    //循环不断的读取消息
    loop {
        //获取客户端发送过来的消息
        let bytes_read = stream.read(&mut buf)?;
        //转换成字符串
        let s = str::from_utf8_mut(&mut buf[0..bytes_read])
        //打印字符串
        println!("{:?}",s);
        //将接受的字符串返回发送端
        stream.write(&buf[..bytes_read])?;
               
        if bytes_read == 0{
            return Ok(());
        }
    }
}

fn main() -> std::io::Result<()> {
    //监听127.0.0.1 ip ,8080 端口
    let listener = TcpListener::bind("127.0.0.1:8080")?;
    //保存客户端连接对象的集合
    let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();

    for stream in listener.incoming() {
        let stream = stream.expect("failed!");
        let handle = thread::spawn(move || {
            handle_client(stream)
        .unwrap_or_else(|error| eprintln!("{:?}", error));
        });

        thread_vec.push(handle);
    }

    for handle in thread_vec {
        handle.join().unwrap();
    }

    Ok(())
}

